#include "FDEBEdge.h"
#include <unordered_map>


FDEBEdge::FDEBEdge(const FPoint& source, const FPoint& target)
    : source(source), target(target) {}

void FDEBEdge::initializeSubdivisionPoints(int P) {
    subdivisionPoints.clear();
    for (int i = 0; i <= P + 1; ++i) {
        double t = static_cast<double>(i) / (P + 1);
        subdivisionPoints.push_back(interpolate(source, target, t));
    }
}

void FDEBEdge::refineSubdivisionPoints() {
    std::vector<FPoint> newPoints;
    newPoints.push_back(subdivisionPoints[0]);

    for (size_t i = 0; i < subdivisionPoints.size() - 1; ++i) {
        const FPoint& p = subdivisionPoints[i];
        const FPoint& q = subdivisionPoints[i + 1];
        FPoint mid = interpolate(p, q, 0.5);
        newPoints.push_back(mid);
        newPoints.push_back(q);
    }

    subdivisionPoints = newPoints;
}


std::vector<FDEBEdge> buildFDEBEdges(
    const std::vector<Edge>& rawEdges,
    const std::vector<Node>& rawNodes,
    int P
) {
    // 先构建节点查找表（用unordered_map提高效率）
    std::unordered_map<int, Node> nodeMap;
    for (const Node& node : rawNodes) {
        nodeMap[node.id] = node;
    }

    std::vector<FDEBEdge> fdebEdges;
    for (const Edge& e : rawEdges) {
        auto itSource = nodeMap.find(e.from);
        auto itTarget = nodeMap.find(e.to);

        if (itSource == nodeMap.end() || itTarget == nodeMap.end()) continue;

        FPoint source = { itSource->second.lon, itSource->second.lat };
        FPoint target = { itTarget->second.lon, itTarget->second.lat };

        FDEBEdge edge(source, target);
        edge.initializeSubdivisionPoints(P);

        fdebEdges.push_back(std::move(edge));
    }

    return fdebEdges;
}